package initialize

import (
	"fmt"
	klog "github.com/go-kratos/kratos/v2/log"
	"github.com/jinzhu/copier"
	zlog "github.com/jiushengTech/common/log/zap"
	zconf "github.com/jiushengTech/common/log/zap/conf"
	"go.uber.org/zap"
	"transfer-service/internal/conf"
	"transfer-service/internal/global"
)

var _ klog.Logger = (*Logger)(nil)

// Logger 实现了klog.Logger接口
type Logger struct {
	Logger *zap.Logger
}

func InitZap(conf *conf.Log_Zap) {
	c := zconf.ZapConf{}
	err := copier.Copy(&c, conf)
	if err != nil {
		panic(err)
	}
	logger := zlog.NewZapLogger(&c)
	global.LOG = klog.NewHelper(&Logger{Logger: logger})
	global.LOG.Info("zap初始化成功")
}

// Log 实现klog.Logger接口的Log方法
func (z *Logger) Log(level klog.Level, keyvals ...interface{}) error {
	// 验证输入参数
	if len(keyvals) == 0 || len(keyvals)%2 != 0 {
		z.Logger.Warn("Keyvalues must appear in pairs", zap.Any("keyvals", keyvals))
		return nil
	}

	// 构建日志字段
	fields := make([]zap.Field, 0, len(keyvals)/2)
	for i := 0; i < len(keyvals); i += 2 {
		key := fmt.Sprint(keyvals[i])
		fields = append(fields, zap.Any(key, keyvals[i+1]))
	}

	// 根据日志级别记录日志
	switch level {
	case klog.LevelDebug:
		z.Logger.Debug("", fields...)
	case klog.LevelInfo:
		z.Logger.Info("", fields...)
	case klog.LevelWarn:
		z.Logger.Warn("", fields...)
	case klog.LevelError:
		z.Logger.Error("", fields...)
	case klog.LevelFatal:
		z.Logger.Fatal("", fields...)
	}

	return nil
}
